<template>
  <div class="pagination">
    <button :disabled="currentPageNum===1" @click="$emit('changeNo',currentPageNum-1)">上一页</button>
    <button v-if="startEnd.start>1" @click="$emit('changeNo',1)">1</button>

    <button v-if="startEnd.start>2">···</button>
<!-- v-for和v-if同时使用时 v-for的优先级高-->

    <button
        :class="{active:page===currentPageNum}"
        v-for="page in startEnd.end " :key="page"
        @click="$emit('changeNo',page)"
        v-if="page>=startEnd.start"
    >{{page}}
    </button>


    <button v-if="startEnd.end<totalPages-1">···</button>
    <button v-if="startEnd.end<totalPages" @click="$emit('changeNo',totalPages)">共{{ totalPages }}页</button>
    <button
        :disabled="currentPageNum===totalPages"
        @click="$emit('changeNo',currentPageNum+1)"
    >下一页
    </button>

    <button style="margin-left: 30px">共{{ total }}条</button>
  </div>
</template>

<script>

export default {
  name: "Pagination",
  //// props接收的属性数据  computed计算的数据  以及data里面的数据
  // 最终都是可以通过vm进行访问的
  props: {
    currentPageNum: {
      type: Number,
      required: true//必传项
    },
    total: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      required: true
    },
    continueNum: {
      type: Number,
      default: 5
    }
  },
  computed: {
    //计算总页数
    totalPages() {
      return Math.ceil(this.total / this.pageSize)
    },
    //根据当前页的不同计算连续也的起始位置和结束位置
    startEnd() {
      let {currentPageNum, total, continueNum, pageSize, totalPages} = this
      let start = 0
      let end = 0
      if (continueNum > totalPages) {
        start = 1,
            end = totalPages
      } else {
        //先考虑所有的情况都是在中间的 在考虑其他的
        start = currentPageNum - Math.floor(continueNum / 2)
        end = currentPageNum + Math.floor(continueNum / 2)
        //左侧不正常需要修改
        if (start < 0) {
          start = 1,
              end = continueNum
        }
        if (end > totalPages) {
          start = totalPages - continueNum + 1
          end = totalPages
        }
      }
      return {start, end}
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>

